package vader.util;

import org.apache.commons.lang3.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import javax.servlet.http.HttpServletRequest;
import java.net.InetAddress;
import java.net.UnknownHostException;

/**
 * IP地址相关工具类
 *
 * @author
 */
public class IpUtil {

    private static final Log logger = LogFactory.getLog(IpUtil.class);

    private static final String localIp = "127.0.0.1";
    private static final String unKnownIp = "unknown";

    public static Long getLongIpAddr(HttpServletRequest request) {
        String ipAddr = getIpAddr(request);
        logger.debug("ipAddr :"+ipAddr);
        if (StringUtils.isEmpty(ipAddr)) {
            ipAddr = "0";
        }
        return ipToNumber(ipAddr);

    }

    private static Long ipToNumber(String ip) {
        Long ips = 0L;
        String[] numbers = ip.split("\\.");
        if (numbers.length > 4) {
            //等价上面
            for (int i = 0; i < 4; ++i) {
                ips = ips << 8 | Integer.parseInt(numbers[i]);
            }
        }
        return ips;
    }

    private static String numberToIp(Long number) {
        //等价上面
        String ip = "";
        for (int i = 3; i >= 0; i--) {
            ip += String.valueOf((number & 0xff));
            if (i != 0) {
                ip += ".";
            }
            number = number >> 8;
        }

        return ip;
    }


    public static String getIpAddr(HttpServletRequest request) {

        if (request == null) {
            return StringUtils.EMPTY;
        }
        String ipAddress;
        try {
            ipAddress = request.getHeader("x-forwarded-for");
            if (ipAddress == null || ipAddress.length() == 0 || unKnownIp.equalsIgnoreCase(ipAddress)) {
                ipAddress = request.getHeader("Proxy-Client-IP");
            }
            if (ipAddress == null || ipAddress.length() == 0 || unKnownIp.equalsIgnoreCase(ipAddress)) {
                ipAddress = request.getHeader("WL-Proxy-Client-IP");
            }
            if (ipAddress == null || ipAddress.length() == 0 || unKnownIp.equalsIgnoreCase(ipAddress)) {
                ipAddress = request.getRemoteAddr();
                if (localIp.equals(ipAddress)) {
                    // 根据网卡取本机配置的IP
                    InetAddress inet = null;
                    try {
                        inet = InetAddress.getLocalHost();
                    } catch (UnknownHostException e) {
                        logger.error(e.getMessage(), e);
                    }
                    ipAddress = inet!= null ?inet.getHostAddress():"";
                }
            }
            // 对于通过多个代理的情况，第一个IP为客户端真实IP,多个IP按照','分割
            // "***.***.***.***".length()
            if (ipAddress != null && ipAddress.length() > 15) {
                // = 15
                if (ipAddress.indexOf(",") > 0) {
                    ipAddress = ipAddress.substring(0, ipAddress.indexOf(","));
                }
            }
        } catch (Exception e) {
            ipAddress = "";
        }

        return ipAddress;
    }


}
